package net.guerlab.smart.wx.auth.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import net.guerlab.smart.platform.basic.auth.utils.AbstractJwtHelper;
import net.guerlab.smart.wx.auth.properties.WxUserJwtProperties;
import net.guerlab.smart.wx.core.WxUserAuthConstants;
import net.guerlab.smart.wx.core.entity.IJwtInfo;
import net.guerlab.smart.wx.core.entity.JwtInfo;
import org.apache.commons.lang3.StringUtils;

/**
 * jwt助手
 *
 * @author guer
 */
public class WxUserJwtHelper extends AbstractJwtHelper<IJwtInfo, WxUserJwtProperties> {

    /**
     * 签名前缀
     */
    public static final String PREFIX = "WX_USER_JWT";

    @Override
    protected void generateToken0(JwtBuilder builder, IJwtInfo user) {
        Boolean activated = user.getActivated();

        builder.setSubject(user.getNickName());
        builder.claim(WxUserAuthConstants.OPEN_ID, StringUtils.trimToEmpty(user.getOpenId()));
        builder.claim(WxUserAuthConstants.UNION_ID, StringUtils.trimToEmpty(user.getUnionId()));
        builder.claim(WxUserAuthConstants.APP_ID, StringUtils.trimToEmpty(user.getAppId()));
        builder.claim(WxUserAuthConstants.AVATAR_URL, StringUtils.trimToEmpty(user.getAvatarUrl()));
        builder.claim(WxUserAuthConstants.ACTIVATED, activated == null ? false : activated);
    }

    @Override
    protected IJwtInfo parse0(Claims body) {
        String openId = body.get(WxUserAuthConstants.OPEN_ID, String.class);
        String unionId = body.get(WxUserAuthConstants.UNION_ID, String.class);
        String appId = body.get(WxUserAuthConstants.APP_ID, String.class);
        String nickName = body.getSubject();
        String avatarUrl = body.get(WxUserAuthConstants.AVATAR_URL, String.class);
        Boolean activated = body.get(WxUserAuthConstants.ACTIVATED, Boolean.class);

        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setOpenId(openId);
        jwtInfo.setUnionId(unionId);
        jwtInfo.setAppId(appId);
        jwtInfo.setNickName(nickName);
        jwtInfo.setAvatarUrl(avatarUrl);
        jwtInfo.setActivated(activated);

        return jwtInfo;
    }

    @Override
    protected String getPrefix() {
        return PREFIX;
    }
}
